#!/usr/local/bin/tea


require.paths.unshift("./code");

/* simple HTTP server; listens on 127.0.0.1:10001 and returns HTTP/200 OK */
var Socket = require("socket").Socket;
var Buffer = require("binary").Buffer;
var http = require("http");

var LNHTTPServer=require("standalone/HTTPServer").LNHTTPServer;
var LNServer=require('server/Server').LNServer;

var LNComet=require("standalone/Comet").LNComet;
var clients=[];





function main(IP,PORT)
{
	var comet=new LNComet();
	var app=new LNServer();
	var server=new LNHTTPServer({address:IP,port:PORT,clients:clients,app:app,comet:comet});
	while(1) {	
		var sockets=[server.socket];
		for (var i=0;i<clients.length;i++) sockets.push(clients[i].socket);
		//if (sockets.length) system.stdout.writeLine("main() - sockets.length="+sockets.length+" before select");
		var result=Socket.select(sockets,[],[],1000);
		if (!result) continue;
		//if (sockets.length) system.stdout.writeLine("main() - sockets.length="+sockets.length+" after select");
		for (var i=0;i<sockets.length;i++) {
			var s=sockets[i];
			if (s===server.socket) {
				server.action();
				break;
			}
			for (var j=0;j<clients.length;j++) {
				var clt=clients[j];
				if (!(clt.socket===s)) continue;
				if (!clt.action()) continue;
				server.remove_client_by_socket(clt.socket);
			}
		}
	}
}

//system.stdout.writeLine(system.args.join(" "));
if (system.args.length==3) {
	main(system.args[1],system.args[2]);
} else {
	system.stdout.writeLine("Usage:\n"+system.args[0]+" IP PORT\n");
}

/*

while (1) {
	var connection = socket.accept();
	var data = "", buffer = "";
	while (1) {
		buffer = connection.receive(1000);
		if (!buffer) { break; }
		data += buffer.toString("ascii");
		if (data.indexOf("\n\n") == data.length-2) { break; }
		if (data.indexOf("\r\n\r\n") == data.length-4) { break; }
	}
	connection.send("HTTP/1.0 200 OK\n\nHello world .)");
	connection.close();	
	if (data.match(/quit/i)) { break; }
}
socket.close();
*/
